#!/usr/bin/python

from rest_framework.exceptions import ValidationError, NotAuthenticated, AuthenticationFailed, MethodNotAllowed
from rest_framework.views import exception_handler

from exception import BusinessException
from response import APIResponse


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None:
        response = APIResponse.error(message=str(exc))

    elif isinstance(exc, BusinessException):
        response = APIResponse.error(message=exc.message)

    elif isinstance(exc, MethodNotAllowed):
        response = APIResponse.bad_request(message="请求方式错误")

    elif isinstance(exc, NotAuthenticated):
        response = APIResponse.unauthorized()

    elif isinstance(exc, AuthenticationFailed):
        response = APIResponse.unauthorized()

    elif isinstance(exc, ValidationError):
        error_key = next(iter(exc.detail))
        error_msg = exc.detail.get(error_key)[0]
        response = APIResponse.bad_request(message=error_msg)
    else:
        response = APIResponse.unknown(message=str(exc))

    return response
